package thread.wang_bao_ling.c20;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * @Auther: luobiao
 * @Date: 2021/3/19 06:15
 * @Description:
 * 内部基于堆实现，队列中的元素需要实现Comparable或创建PriorityBlockingQueue时传入比较器来确认优先级。需要注意的是创建PriorityBlockingQueue时只能指定初始容量大小
 * 当达到初始容量时会扩容，所以对写操作是没有限制的，要注意内存溢出的问题

 */
public class PriorityBlockingQueueTest {
    public static void main(String[] args) {
       /*  PriorityBlockingQueue<User> queue=new PriorityBlockingQueue(3, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.age < o2.age ? -1 : 1;
            }
        });*/

        PriorityBlockingQueue<User> queue = new PriorityBlockingQueue(3);//3指定的是初始容量
        queue.add(new User("张三",20));
        queue.add(new User("李四",40));
        queue.add(new User("王五",30));
        queue.add(new User("田六",10));
        while (queue.size() > 0) {
            System.out.println(queue.remove().name);
        }
    }
    public static class User implements Comparable<User>{
        public String name;
        public Integer age;

        public User(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public int compareTo(User o) {
            //按年龄从小到大优先排序
            return this.age < o.age  ? -1: 1;
        }
    }
}
